package Network.Echo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Udp回显服务器,服务端代码
 */
public class UdpEchoServer {
    public DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //1.接收客户端请求
            DatagramPacket req = new DatagramPacket(new byte[4096],4096);
            socket.receive(req);
            //2.处理数据,直接返回
            //先将请求转换成字符串
            String resp = new String(req.getData(),0,req.getLength());
            //处理请求
            DatagramPacket respData = new DatagramPacket(resp.getBytes(),0,resp.getBytes().length,req.getSocketAddress());
            socket.send(respData);
            System.out.printf("[%s:%d] req:%s ,resp:%s",req.getAddress(),req.getPort(),req.getData(),resp);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();

    }
}
